import json
import random
import time

import redis
import requests
from flask import Blueprint, send_file, make_response, redirect
from flask_restful import Resource
from ronglian_sms_sdk import SmsSDK
from tools.my_jwt import jj

from app import db
from tools.captcha.captcha import captcha
from tools.comm import sendMsg
from tools.myredis import r
from application.models.users.user import SfLogin

from application.models.users.user import User
from flask import Blueprint,request,jsonify
user_blue = Blueprint("userblue",__name__)
from captcha.image import ImageCaptcha

@user_blue.route('/text')
def get():
    return jsonify({'code':200,'msg':'mes'})



@user_blue.route('/getcode')
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    r.str_add(uuid,text)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res


@user_blue.route('/sendSmsCode',methods=['post'])
def sendSmsCode():
    data = request.data
    if data:
        # 获取3个参数
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        # redis中获取图片验证码
        value = r.str_get(uuid)
        # 对redis中获取的图片验证码解析
        value1 = value.decode()
        print(value1)
        # 如果图片验证码存在
        if value:
            # 将前端输入的验证码和图片验证码转为大小写 做对比
            if piccode.lower()==value1.lower():
                # 把redis里面存的手机号获取出来 然后赋值给mcode
                mcode = r.str_get(mobile)
                # 如果手机号存在
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                # 调用random生成随机数
                scode = random.randint(10000,99999)
                # 把容连云赋值到flag里面
                flag = sendMsg(mobile,scode)
                # 如果flag存在
                if flag:
                    # 就把手机号加入到redis里面 一分钟
                    r.str_setex(mobile,scode,60)
                    # 判断完图形验证码之后 删除redis里面的图形验证码
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})

        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})


@user_blue.route('/login',methods=['POST'])
# 注册登录接口
def login():
    # 获取前端返回的数据
    data = request.data
    # 如果存在
    if data:
        # 把获取到的data 转化json格式赋值到data里面
        data = json.loads(data)
        # 获取参数
        mcode = data['code']
        mobile = data['mobile']
        # 获取到redis里面存储的手机号
        code = r.str_get(mobile)
        # 如果手机号存在
        if code:
            #
            if int(code)==int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                # 用户信息生成jwt token
                token = jj.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
                return jsonify({'code':200,'token':token,'userid':user.id})
            else:
                return jsonify({'code':10021,'msg':'验证码错误'})
        else:
            return jsonify({'code':10020,'msg':''})

# 获取weibo地址
@user_blue.route('/sf_login')
def getwburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询数据库中是否存在，如果存在用户信息生成jwt token 返回
    sql = 'select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid=%s'%(uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {'data':{'userid':i[0],'exp':int(time.time())}}
            token = jj.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid="+str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面，token uid 传递过去
    return redirect("http://localhost:8080/#/banding?uid="+uid+"&token="+token)

# 绑定手机号
@user_blue.route('/bandMobile',methods=['POST'])
def bandMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    print(mobile,'>>>>>>>>>>>>>>>>>>>>>>>>>..')
    # 先查询用户表，如果手机号存在，获取userid,写入三方登录表，生成token返回
    user = User.query.filter(User.mobile==mobile).first()
    print(user)
    if not user:
        # 添加用户
        u = User(mobile=mobile,nikename=mobile)
        print(u)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile==mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid,写入三方登录表，生成token返回
    data = {'data':user.id,'exp':int(time.time())}
    token = jj.jwt_encode(data)
    return jsonify({'userid':str(user.id),'token':token})

